package com.test.moredatesouce.common.database;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author:ZhouYang
 * @Description:
 * @Date: Created in 2019/9/2 14:02
 * @Modified By：DB1数据源配置
 */

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = DataSourceDB1.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class DataSourceDB1 {

    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.test.moredatesouce.modules.other.db1.mapper";
    static final String MAPPER_LOCATION = "classpath*:/mapper/db1/*.xml";

    @Value("${spring.datasource.ds1.url}")
    private String url;

    @Value("${spring.datasource.ds1.username}")
    private String user;

    @Value("${spring.datasource.ds1.password}")
    private String password;

    @Value("${spring.datasource.ds1.driver-class-name}")
    private String driverClass;

    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(DataSourceDB1.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}
